package com.iwe.crm.base.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //把Mysql数据封装到Redis中 emp: good: cart:
    public <T> void mysqlToRedis(String keyPattern, List<T> data){
        ValueOperations<String, String> vo = redisTemplate.opsForValue();
        HashOperations<String, Object, Object> hash =
                redisTemplate.opsForHash();
        for (T t : data) {
            String key = keyPattern + vo.increment("index");
            Map<String,Object> map = new HashMap<>();
            BeanUtil.beanToMap(t,map,new CopyOptions().ignoreNullValue());
            hash.putAll(key,map);
        }
    }

    //把Redis数据取出来封装到对象中
    public <T> List<T> redisToBean(Class<T> tClass,String keyPattern){
        HashOperations<String, Object, Object> hash =
                redisTemplate.opsForHash();
        Set<String> keys = redisTemplate.keys(keyPattern);

        List<T> list = new ArrayList<>();
        for (String key : keys) {
            Map<Object, Object> entries = hash.entries(key);
           T t = BeanUtil.mapToBean(entries, tClass,
                    false, new CopyOptions().ignoreNullValue());
            list.add(t);
        }
        return list;
    }
}
